package com.tencent.wxcloudrun.vpnmanagement.pwdmanagement;

import com.tencent.wxcloudrun.vpnmanagement.base.Result;
import com.tencent.wxcloudrun.vpnmanagement.tools.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Random;

@RestController
@ResponseBody
@RequestMapping("/api/my")
public class PwdManagementController {
    @Autowired
    private JwtUtil jwtUtil;

    @RequestMapping("/getpwd")
    public Result getPwd(){
        String poneNum = this.getUserIdFromToken();
        if(true) {
            Random random = new Random();
            int pwd = random.nextInt(899999);
            pwd = pwd+100000;
            /*
             * 向服务器发送临时密码
             * */
            return Result.ok(pwd);
        }
        return Result.error("你没有权限");
    }



    private String getUserIdFromToken(){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String authHeader = request.getHeader("Authorization");
        if(authHeader!=null && authHeader.startsWith("Bearer ")){
            final String token = authHeader.substring(7);
            Claims claims = jwtUtil.parseJWT(token);
            if(claims!=null){
                String phoneNum = (String) claims.get("phoneNum");
                return phoneNum;
            }
        }
        return null;
    }
}
